package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.feigns.AdminFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.exception.CustException;
import com.heima.model.threadLocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private GreenScan greenScan;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //1. 校验参数
        //   评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        Integer size = dto.getSize();
        Date minDate = dto.getMinDate();
        if (size == null || size == 0) {
            size = 10;
        }
        if (minDate == null) {
            minDate = new Date();
        }
        //2. 条件查询评论回复信息
        //条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(minDate));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        query.limit(size);
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);
        List<String> ids = apCommentRepayList.stream().map(m ->
                m.getId()
        ).collect(Collectors.toList());
        //3. 检查是否登录
        ApUser loginUser = AppThreadLocalUtils.getUser();
        if (loginUser == null) {
            //3.1 如果未登录直接 返回评论回复列表
            return ResponseResult.okResult(apCommentRepayList);
        }
        //3.2 如果登录，需要判断哪些回复点过赞
        //思路:
        //基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        Query query1 = Query.query(Criteria.where("commentRepayId").in(ids).and("authorId").is(loginUser.getId()));
        List<ApCommentRepayLike> commentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        //遍历 当前回复列表，将每一个回复信息 封装成 vo
        List<ApCommentRepayVO> result = new ArrayList<>();
        for (ApCommentRepay commentRepay : apCommentRepayList) {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(commentRepay, apCommentRepayVO);
            //判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
            ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("commentRepayId").is(commentRepay.getId())), ApCommentRepayLike.class);
            boolean contains = commentRepayLikes.contains(commentRepayLike);
            if (contains) {
                apCommentRepayVO.setOperation((short) 0);
            }
            result.add(apCommentRepayVO);
        }
        return ResponseResult.okResult(result);
    }

    /**
     * 保存回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验:
        //  是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser loginUser = AppThreadLocalUtils.getUser();
        if (loginUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "当前用户未登录");
        }
        //  回复内容安全校验
        //  简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        String content = dto.getContent();
        boolean sensitive = handleSensitive(content);
        if (!sensitive) {
            // 有敏感词
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "评论中含有敏感词");
        }
        boolean scanContent = scanContent(content);
        if (!scanContent) {
            // 有违规内容
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "评论中含有违规内容");
        }
        //2. 根据评论id查询评论信息  检查是否存在
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(dto.getCommentId())), ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论信息不存在!");
        }
        //3. 保存评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setAuthorId(loginUser.getId());
        apCommentRepay.setAuthorName(loginUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        ApCommentRepay save = mongoTemplate.save(apCommentRepay);
        log.info("保存的数据: ====== {}", save);
        //4. 修改评论信息中回复数量 + 1
        Update update = new Update();
        Integer reply = apComment.getReply();
        reply += 1;
        update.set("reply", reply);
        UpdateResult updateResult = mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(dto.getCommentId())), update, ApComment.class);
        log.info("修改后的数据: ====== {}", updateResult);
        return ResponseResult.okResult("回复成功");
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //回复id不能为空   operation 必须 0 或 1
        //校验登录  (必须登录)
        ApUser loginUser = AppThreadLocalUtils.getUser();
        if (loginUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_ADMIND);
        }
        //校验回复信息是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(Query.query(Criteria.where("id").is(dto.getCommentRepayId())), ApCommentRepay.class);
        if (apCommentRepay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "需要回复的评论信息不存在");
        }
        //2. 如果是点赞  判断是否点过赞
        Integer likes = apCommentRepay.getLikes();
        if ((short) 0 == dto.getOperation()) {
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId())), ApCommentRepayLike.class);
            if (apCommentRepayLike != null) {
                //点过赞提示请勿重复点赞
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "您已经点过赞了");
            }
            //未点过赞， 保存点赞信息
            ApCommentRepayLike newCommentRepayLike = new ApCommentRepayLike();
            newCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            newCommentRepayLike.setOperation((short) 0);
            newCommentRepayLike.setAuthorId(loginUser.getId());
            ApCommentRepayLike save = mongoTemplate.save(newCommentRepayLike);
            log.info("保存的数据是 {}", save);
            //并将回复信息的点赞数量字段+1
            likes += 1;
            Update update = new Update();
            update.set("likes", likes);
            UpdateResult updateResult = mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(dto.getCommentRepayId())), update, ApCommentRepay.class);
            log.info("修改后的数据: ====== {}", updateResult);
        } else {
            //3. 如果是取消赞
            //删除点赞信息
            Query query = Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId").is(loginUser.getId()));
            DeleteResult remove = mongoTemplate.remove(query, ApCommentRepayLike.class);
            log.info("删除的数据是: {}", remove);
            //并将回复信息的点赞数量字段( - 1) , 要判断下别减成负数
            likes -= 1;
            if (likes <= 0) {
                likes = 0;
            }
            Update update = new Update();
            update.set("likes", likes);
            UpdateResult updateResult = mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(dto.getCommentRepayId())), update, ApCommentRepay.class);
            log.info("修改后的数据: ====== {}", updateResult);
        }
        //4. 返回当前回复的最新点赞数量      数据的key:  likes
        Map<String, Object> result = new HashMap<>();
        result.put("likes", likes);
        return ResponseResult.okResult(result);
    }

    /**
     * 扫描是否有敏感词 有则返回false 没有就返回 true
     *
     * @param content
     * @return
     */
    private boolean handleSensitive(String content) {
        boolean flag = true;// 默认没有敏感词
        // 1 远程调用查询敏感词
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        // 2 判断远程调用是否成功
        if (!sensitives.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用失败");
        }
        // 3 获取敏感词 将敏感词转为DFA数据
        List<String> data = sensitives.getData();
        SensitiveWordUtil.initMap(data);
        // 4 基于DFA扫描,内容中是否存在敏感词
        Map<String, Integer> matchWords = SensitiveWordUtil.matchWords(content);
        // 5 判断是否存在敏感词 有 则将文章状态修改为2
        if (!CollectionUtils.isEmpty(matchWords)) {
            log.error("评论中包含以下敏感词汇" + matchWords.toString());
            flag = false;
        }
        return flag;
    }

    /**
     * aliyun扫描文本
     *
     * @param content
     * @return
     */
    private boolean scanContent(String content) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            // 返回的suggestion 有三种模式 block: 违规 review 需要进一步人工审核 pass 通过
            String suggestion = scanResult.getSuggestion();
            // 根据suggestion来选择进行具体操作
            switch (suggestion) {
                case "block":
                    // 失败 状态要改为2
                    log.error("评论中包含敏感词汇");
                    break;
                case "review":
                    // 人工 状态改为3
                    log.error("评论中包含敏感词汇");
                    break;
                case "pass":
                    // 审核通过
                    flag = true;
                    log.info("审核通过");
                    break;
                default:
                    log.error("评论中包含敏感词汇");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
